package tenant

import (
	"context"
	"encoding/json"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/tenant/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/model/entity"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/cache"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/utils"

	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
	// 加强数据校验
	cc, _ := cache.NewCache()
	cache.InitCache(ctx, consts.InitialCacheKeys.RegionsKey, false)
	val, err := cc.Get(ctx, consts.InitialCacheKeys.RegionsKey)
	if err != nil {
		return nil, gerror.WrapCode(consts.GetCacheFailed, err)
	}
	regionStr, ok := val.Val().(string)
	if !ok {
		return nil, gerror.WrapCode(consts.ParseCacheFailed, gerror.New("行政缓存存储出错"))
	}
	regionMap := make(map[string]entity.Region, 0)
	json.Unmarshal([]byte(regionStr), &regionMap)

	if len(req.CountryCode) > 0 {
		if _, ok := regionMap[req.CountryCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, gerror.New(req.CountryCode))
		}
	}
	if len(req.ProvinceCode) > 0 {
		if _, ok := regionMap[req.ProvinceCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, gerror.New(req.ProvinceCode))
		}
	}
	if len(req.CityCode) > 0 {
		if _, ok := regionMap[req.CityCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, gerror.New(req.CityCode))
		}
	}
	if len(req.CountyCode) > 0 {
		if _, ok := regionMap[req.CountyCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, gerror.New(req.CountyCode))
		}
	}
	in := &v1.UpdateInput{}
	utils.CopyStruc(*req, in)
	in.Id = req.Id

	// in.Status = req.Status
	// if req.CountryCode != "" {
	// 	in.CountryCode = req.CountryCode
	// }
	// if req.ProvinceCode != "" {
	// 	in.ProvinceCode = req.ProvinceCode
	// }
	// if req.CityCode != "" {
	// 	in.CityCode = req.CityCode
	// }
	// if req.CountyCode != "" {
	// 	in.CountyCode = req.CountyCode
	// }
	// if req.Address != "" {
	// 	in.Address = req.Address
	// }
	// if req.Contact != "" {
	// 	in.Contact = req.Contact
	// }
	// if req.Phone != "" {
	// 	in.Phone = req.Phone
	// }
	out, err := service.Tenant().Update(ctx, in)
	if err != nil {
		return nil, err
	}
	res = &v1.UpdateRes{Rows: out.Rows}
	return res, nil
}
